import {getVal} from './utils.js'

let template = null

function compiler (vm){
    console.log('compiler')
    if(!template){
        template  = vm.$el.innerHTML
    }
    vm.$el.innerHTML = '';
    vm.$el.appendChild(merge(vm, inner2HTML(template)))
}

function inner2HTML (html){
    var div = document.createElement('div')
    div.innerHTML = html
    return div
}

const reg = /{{(\S*)}}/

function merge(vm, el) {

    var fragment = document.createDocumentFragment()
    // let nodes = el.childNodes
    let firstChild


    while(firstChild = el.firstChild){
      if(firstChild.nodeType === 1){
           // ELEMENT
          firstChild.appendChild(merge(vm, firstChild))
      }else if(firstChild.nodeType === 3){
          // TEXT
          let text = firstChild.textContent
          if(text.match(reg)){
              let alias = reg.exec(text)[1]
              firstChild.textContent = text.replace(reg, getVal(vm,alias))
          }
      }
      fragment.appendChild(firstChild)
    }


    return fragment
}

export default compiler
